const axios = require('axios');
const allServices = require('../db');
const config = require('../config')

const searchApi = async (keyWords) => {
  const res = await axios.post(config.HOST + '/juno/api/v2/search/universal_search_v2.json', {
    q: keyWords,
    size: 1000,
    search_type: 1091,
  })
  const dishArr = res.data.content.content
  const insertData = []
  dishArr.forEach(async item => {
    const singleDish = item.content.object
    if (singleDish) {
      const image = singleDish.image.ident
      if (image) {
        const data = [
          singleDish.id,
          singleDish.image.ident,
          singleDish.name,
          singleDish.author.name,
          singleDish.author.image.ident,
          singleDish.score,
          singleDish.desc,
        ]
        insertData.push(data)
        try {
          await allServices.addDish(data)
        } catch (error) {
          allServices.addErrorLog([error.sqlMessage,singleDish.id])
        }
      }
    }
  })
}

exports.searchApi = searchApi